package cn.cscamp.middleware.loadbalancer;

import cn.cscamp.middleware.loadbalancer.config.LoadbalancerServiceConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
@ConditionalOnProperty(name = "loadbalancer.enabled", havingValue = "true")
@EnableConfigurationProperties(LoadbalancerServiceConfig.class)
public class RetryWebClientAutoConfiguration {

    @ConditionalOnMissingBean
    @Bean
    public RetryWebClientFactory retryWebClientFactory(LoadbalancerServiceConfig loadbalancerServiceConfig) {
        WebClient.Builder builder = WebClient.builder();
        RetryWebClientFactory retryWebClientFactory = new RetryWebClientFactory(builder);
        CustomRetryableLoadBalancerExchangeFilterFunction exchangeFilterFunction = new CustomRetryableLoadBalancerExchangeFilterFunction(loadbalancerServiceConfig);
        retryWebClientFactory.filter(exchangeFilterFunction);
        return retryWebClientFactory;
    }
}
